import {
  ariaDescribedByIds,
  FormContextType,
  RJSFSchema,
  StrictRJSFSchema,
  WidgetProps,
} from '@rjsf/utils';
import { FocusEvent } from 'react';
import { ReactComponent as Reverse1 } from '../../assets/svg-icons/commands/common/flip-direction-1.svg';
import { ReactComponent as Reverse2 } from '../../assets/svg-icons/commands/common/flip-direction-2.svg';
import './ReverseIconWidget.scss';

export default function ReverseIconWidget<
  T = any,
  S extends StrictRJSFSchema = RJSFSchema,
  F extends FormContextType = any,
>(props: WidgetProps<T, S, F>) {
  const { disabled, id, onBlur, onChange, onFocus, value } = props;

  const handleChange = () => onChange(!value);
  const handleBlur = ({ target }: FocusEvent<HTMLInputElement>) =>
    onBlur(id, target.checked);

  const handleFocus = ({ target }: FocusEvent<HTMLInputElement>) =>
    onFocus(id, target.checked);

  const Icon = value ? Reverse1 : Reverse2;

  return (
    <span
      className={`reverse-icon-widget ${disabled ? 'text-gray-400 cursor-not-allowed disabled' : 'cursor-pointer'}`}
      onClick={!disabled ? handleChange : undefined}
      onBlur={!disabled ? handleBlur : undefined}
      onFocus={!disabled ? handleFocus : undefined}
      aria-describedby={ariaDescribedByIds<T>(id)}
    >
      <Icon className='w-4 h-4' />
    </span>
  );
}
